package com.example.roomdemo;

import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;
import com.example.roomdemo.databinding.ItemStudentBinding;
import java.util.List;

/**
 * @author: tuyrt7 on 2020/9/4.
 */
public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.ViewHolder> {

    private Context mContext;
    private List<Student> mStudentList;
    private final LayoutInflater mInflater;
    private onItemClickListener mListener;

    public StudentAdapter(Context context, List<Student> studentList) {
        mContext = context;
        mStudentList = studentList;
        mInflater = LayoutInflater.from(context);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemStudentBinding binding = ItemStudentBinding.inflate(mInflater, parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Student student = mStudentList.get(position);
        holder.bindData(student);

        holder.itemView.setOnClickListener(v -> {
            new AlertDialog.Builder(mContext)
                    .setMessage("确认删除?")
                    .setNegativeButton("取消",null)
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            if (mListener != null) {
                                mListener.onItemClickListener(student);
                            }
                        }
                    }).create().show();
        });
    }

    public void setonItemClickListener(onItemClickListener listener) {
        mListener = listener;
    }

    interface onItemClickListener {
        void onItemClickListener(Student student);
    }


    @Override
    public int getItemCount() {
        return mStudentList == null ? 0 : mStudentList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private ItemStudentBinding mBinding;

        public ViewHolder(@NonNull ItemStudentBinding binding) {
            super(binding.getRoot());
            mBinding = binding;
        }

        public void bindData(Student student) {
            mBinding.setStudent(student);
        }
    }
}
